package action.newelifile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Locale;

import org.apache.commons.net.ftp.FTPFile;

import action.adapter.FtpFileAdapter;
import action.adapter.FtpItemServerAdapter;
import action.pojo.FtpConnect;
import action.pojo.LocalFilePojo;
import action.util.FtpConnectSQLITE;
import action.util.LoadSetting;
import action.util.Tool;
import action.util.UsersDAO;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.LayoutInflater.Factory;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class FtpActivity extends Activity {
	Button expandButton,addressButton,switchButton,backButton,changeViewButton,uploadButton,sortButton,multiButton,mBackButton,
	mCopyButton,mCutButton,mDeleteButton,mCancelButton,downloadButton;
	ImageView imageView1,imageView2,imageMobile,imageSdcard;
	GridView gridView;
	ListView listView,listDetailView;
	TextView txtViewEmpty;

	LinearLayout expandLayout;
	Dialog dialog;
	public FtpConnectSQLITE ftpConnectSQLITE;
	ArrayList<FtpConnect> list_ftp;
	ArrayList<FtpConnect> listserver;
	ArrayList<LocalFilePojo> listlocal;
	FtpFileAdapter adapter;
	String[] operator;
	FTPFile[] listfileFTP;
	//	FtpConnect ftpConnect ;
	FtpItemServerAdapter ftpItemServerAdapter;

	final Handler uiHandler=new Handler();
	boolean isUpdateRequired=false;
	TextView tvwaiting;
	LayoutInflater inflaterwaiting;
	View textEntryViewwaiting;
	AlertDialog.Builder builderwaiting;
	AlertDialog alertwaiting;

	ProgressDialog mProgressDialog;
	public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
	public static final int DIALOG_PROGRESS = 1;
	AsyncTask<String, String, Void> asyn;
	public static final int DIALOG_GETTING_FILE =0;

	AsyncTask<String, String, String> asyntask;

	// muti select
	public ArrayList<FtpConnect> multiSelect = new ArrayList<FtpConnect>();
	public ArrayList<String> multiName = new ArrayList<String>();
	public boolean multi = false;
	public int multiAction = 0;
	int sortlist = 0;

	int flagCopyCut = 0; // 1 copy, 2 cut
	long tongmulti=0;


	public boolean isUpdateRequired() {
		return isUpdateRequired;
	}
	public void setUpdateRequired(boolean isUpdateRequired) {
		this.isUpdateRequired = isUpdateRequired;
	}
	public Handler getUiHandler() {
		return uiHandler;
	}

	public AlertDialog getAlertwaiting() {
		return alertwaiting;
	}
	public void setAlertwaiting(AlertDialog alertwaiting) {
		this.alertwaiting = alertwaiting;
	}

	public static int screenheight,screenwidth;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		try{
			LoadSetting.load(this);
			initLocale();
			setContentView(R.layout.main);
			LoadSetting.loadTheme(this);

			ftpConnectSQLITE = new FtpConnectSQLITE(this);
			ftpConnectSQLITE.open();

			Tool.position = 3;
			initAttribute();
			list_ftp= new ArrayList<FtpConnect>();
			initData();
			processButton();

			DisplayMetrics displaymetrics = new DisplayMetrics();
			getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
			screenheight = displaymetrics.heightPixels;
			screenwidth = displaymetrics.widthPixels;

			super.onCreate(savedInstanceState);
		}catch (Exception e) {
			e.printStackTrace();
			Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage( getBaseContext().getPackageName() );
			i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(i);
		}
	}
	public void initLocale(){
		String languageToLoad = Tool.locale(LoadSetting.setting.getLanguage());  
		Locale locale = new Locale(languageToLoad);   
		Locale.setDefault(locale);  
		Configuration config = new Configuration();  
		config.locale = locale;  
		getBaseContext().getResources().updateConfiguration(config,   
				getBaseContext().getResources().getDisplayMetrics());  


	}
	public void initAttribute(){
		expandButton = (Button)findViewById(R.id.expandButton);
		addressButton = (Button)findViewById(R.id.addressButton);
		switchButton = (Button)findViewById(R.id.switchButton);
		backButton = (Button)findViewById(R.id.backButton);
		changeViewButton = (Button)findViewById(R.id.changeViewButton);
		uploadButton = (Button)findViewById(R.id.uploadButton);
		downloadButton = (Button)findViewById(R.id.downloadButton);
		sortButton = (Button)findViewById(R.id.sortButton);
		multiButton = (Button)findViewById(R.id.multiButton);
		mBackButton = (Button)findViewById(R.id.mBackButton);
		mCopyButton = (Button)findViewById(R.id.mCopyButton);
		mCutButton = (Button)findViewById(R.id.mCutButton);
		mDeleteButton = (Button)findViewById(R.id.mDeleteButton);
		mCancelButton = (Button)findViewById(R.id.mCancelButton);

		imageView1 = (ImageView)findViewById(R.id.imageView1);
		imageView2 = (ImageView)findViewById(R.id.imageView2);
		imageMobile = (ImageView)findViewById(R.id.imageMobile);
		imageSdcard = (ImageView)findViewById(R.id.imageSdcard);

		gridView = (GridView)findViewById(R.id.gridView);

		listView = (ListView)findViewById(R.id.listView);
		listDetailView = (ListView)findViewById(R.id.listDetailView);

		txtViewEmpty = (TextView)findViewById(R.id.txtViewEmpty);

		expandLayout = (LinearLayout)findViewById(R.id.expandLayout);

		imageSdcard.setImageResource(R.drawable.ftp);
		switchButton.setText("FTP");

		uploadButton.setVisibility(Button.GONE);
		downloadButton.setVisibility(Button.VISIBLE);

		inflaterwaiting = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);          
		textEntryViewwaiting = inflaterwaiting.inflate(R.layout.waiting, null);
		tvwaiting=(TextView)textEntryViewwaiting.findViewById(R.id.TextView01);					
		tvwaiting.setText("waiting"+"...");

		builderwaiting = new AlertDialog.Builder(FtpActivity.this);
		builderwaiting.setView(textEntryViewwaiting);
		builderwaiting.setCancelable(false);
		alertwaiting = builderwaiting.create();


		Tool.list_favorite_ftp = getAllFavorite();
		if (Tool.list_favorite_ftp == null)
			Tool.list_favorite_ftp = new ArrayList<FtpConnect>();
	}

	// 
	public void loadAllServer(){
		listserver=(ArrayList<FtpConnect>) ftpConnectSQLITE.getAllConnect();
	}

	public void initData(){
			if(Tool.ftp_path!=null && Tool.ftp_path.size()>0){
				Tool.connects();
				refreshItemServerFTP(Tool.connect);
			}else{
				addressButton.setText(R.string.choose_machine);
				listserver = new ArrayList<FtpConnect>();
				refreshFTP();
			}
		}

	public void refreshItemServerFTP(FtpConnect ftpConnect) {
		expandButton.setClickable(true);
		expandButton.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.drawable.plus), null,null);
		addressButton.setClickable(true);
		addressButton.setOnClickListener(processButtonAddress());

		list_ftp = getListFTP(ftpConnect);
		switch (LoadSetting.setting.getDisplay()) {
		case 0:
			initalGridView();
			break;
		case 1:
			initalListView();
			break;
		case 2:
			initalDetailView();
			break;
		default:
			break;
		}	

		System.out.println(" tool path == " + Tool.ftp_path);
		addressButton.setText(Tool.connect.getHostname()+Tool.getFTPPath(Tool.ftp_path));
		System.out.println(" add path == " + Tool.connect.getHostname()+Tool.getFTPPath(Tool.ftp_path));
	}

	public ArrayList<FtpConnect> getListFTP(FtpConnect ftpConnect){
		boolean flag = Tool.connects();
		ArrayList<FtpConnect> ffile = new ArrayList<FtpConnect>();
		ArrayList<FtpConnect> ffolder = new ArrayList<FtpConnect>();
		ArrayList<FtpConnect> lstftp = new ArrayList<FtpConnect>();
		try{
			if(flag){
				listfileFTP= Tool.client.listFiles(Tool.getFTPPath(Tool.ftp_path));
				System.out.println(" list file " + listfileFTP.length);
				if(listfileFTP!=null && listfileFTP.length>0){

					for(FTPFile f : listfileFTP){
						FtpConnect tem = new FtpConnect();
						Drawable icon = null;
						if(f.isFile()){
							if (Tool.checkExtendFile(f.getName(),
							".txt")
							|| Tool.checkExtendFile(
									f.getName(), ".csv")) {
								icon = getResources()
								.getDrawable(
										R.drawable.text_file);
							} else if (Tool.checkExtendFile(
									f.getName(), ".xml")) {
								icon = getResources()
								.getDrawable(
										R.drawable.xml_file);
							} else if (Tool.checkExtendFile(
									f.getName(), ".flv")
									|| Tool.checkExtendFile(
											f.getName(), ".3gp")
											|| Tool.checkExtendFile(
													f.getName(), ".avi")) {										
								icon = getResources().getDrawable(R.drawable.video_file);
							} else if (Tool.checkExtendFile(
									f.getName(), ".mp3")) {
								icon = getResources()
								.getDrawable(
										R.drawable.mp3_file);
							} else if (Tool.checkExtendFile(
									f.getName(), ".doc")
									|| Tool.checkExtendFile(
											f.getName(), ".docx")) {
								icon = getResources()
								.getDrawable(
										R.drawable.word_file);
							} else if (Tool.checkExtendFile(
									f.getName(), ".ppt")
									|| Tool.checkExtendFile(
											f.getName(), ".pptx")) {
								icon = getResources()
								.getDrawable(
										R.drawable.pptx_file);
							} else if (Tool.checkExtendFile(
									f.getName(), ".xls")
									|| Tool.checkExtendFile(
											f.getName(), ".xlsx")) {
								icon = getResources()
								.getDrawable(
										R.drawable.xlsx_file);
							} else if (Tool.checkExtendFile(
									f.getName(), ".zip")
									|| Tool.checkExtendFile(
											f.getName(), ".rar")) {
								icon = getResources()
								.getDrawable(
										R.drawable.rar_file);
							} else if (Tool.checkExtendFile(
									f.getName(), ".jpg")
									|| Tool.checkExtendFile(
											f.getName(), ".jpeg")
											|| Tool.checkExtendFile(
													f.getName(), ".png")
													|| Tool.checkExtendFile(
															f.getName(), ".bmp")
															|| Tool.checkExtendFile(
																	f.getName(), ".gif")) {
								icon = getResources().getDrawable(R.drawable.image_file);
							} else if (Tool.checkExtendFile(
									f.getName(), ".apk")) {
								icon = getResources()
								.getDrawable(
										R.drawable.apk_file);
							} else if (Tool.checkExtendFile(
									f.getName(), ".exe")) {
								icon = getResources()
								.getDrawable(
										R.drawable.exe_file);
							} else {
								icon = getResources()
								.getDrawable(
										R.drawable.unknown_file);
							}

							tem.setHostname(ftpConnect.getHostname());
							tem.setPort(ftpConnect.getPort());
							tem.setUsername(ftpConnect.getUsername());
							tem.setPassword(ftpConnect.getPassword());
							tem.setIcon(icon);
							tem.setFtpFile(f);
							ffile.add(tem);
						}else if(f.isDirectory()){
							icon = getResources().getDrawable(R.drawable.folder_ftp);
							tem.setHostname(ftpConnect.getHostname());
							tem.setPort(ftpConnect.getPort());
							tem.setUsername(ftpConnect.getUsername());
							tem.setPassword(ftpConnect.getPassword());
							tem.setIcon(icon);
							tem.setFtpFile(f);

							ffolder.add(tem);
						}
					}

					//sap xep
					Tool.sortFTP(ffile, 0);
					Tool.sortFTP(ffolder, 0);

					lstftp.clear();
					if(ffolder!=null && ffolder.size()>0)
						lstftp.addAll(ffolder);

					if(ffile!=null && ffile.size()>0)
						lstftp.addAll(ffile);

					/*System.out.println(" size list favorite == " + Tool.list_favorite_ftp.size());
					System.out.println(" lst ftp == " + lstftp.size());
					if(Tool.list_favorite_ftp.size() > 0 && lstftp.size() > 0){
						for(int i = 0;i<Tool.list_favorite_ftp.size();i++){
							for(int y=0;y<lstftp.size();y++){
								System.out.println(" tool list favorite ftp =++ " + Tool.list_favorite_ftp.get(i).getPath());
								System.out.println(" favorite lst ftp y === " +(lstftp.get(y).getHostname()+File.separator+ lstftp.get(y).getFtpFile().getName()));
								if((Tool.list_favorite_ftp.get(i).getPath()).
										equals(lstftp.get(y).getHostname()+File.separator+ lstftp.get(y).getFtpFile().getName())){
									lstftp.get(y).setFavorite(true);
								}
							}
						}
					}*/

				}else{
					lstftp = new ArrayList<FtpConnect>();
				}
			}
			else{
				System.out.println(" connect fail");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return lstftp;

	}

	public void refreshFTP() {
		if (Tool.ftp_path.size() == 0) {
			expandButton.setClickable(false);
			expandButton.setCompoundDrawablesWithIntrinsicBounds(null, null, null,null);
			addressButton.setClickable(false);
		} else {
			expandButton.setClickable(true);
		}
		ftpConnectSQLITE.open();
		loadAllServer();
		switch (LoadSetting.setting.getDisplay()) {
		case 0:
			initalGridView();
			break;
		case 1:
			initalListView();
			break;
		case 2:
			initalDetailView();
			break;
		default:
			break;
		}
	}

	private void initalListView() {
		gridView.setVisibility(GridView.GONE);
		listView.setVisibility(ListView.VISIBLE);
		listDetailView.setVisibility(ListView.GONE);
		txtViewEmpty.setVisibility(TextView.GONE);
		if(Tool.ftp_path.size()==0 &&listserver.size()>0){
			adapter = new FtpFileAdapter(FtpActivity.this, R.layout.list_view, listserver);
			listView.setAdapter(adapter);
			listView.setOnItemClickListener(onListFileClick());
			listView.setOnItemLongClickListener(itemLongClick());
		}
		else if(list_ftp!=null && list_ftp.size()>0){
			ftpItemServerAdapter = new FtpItemServerAdapter(this, R.layout.list_view, list_ftp);
			listView.setAdapter(ftpItemServerAdapter);
			listView.setOnItemClickListener(onListFileItemClick());
			listView.setOnItemLongClickListener(itemFileLongClick());
		}else{
			System.out.println(" vao day khong the");
			listView.setVisibility(ListView.GONE);
			txtViewEmpty.setVisibility(TextView.VISIBLE);
			txtViewEmpty.setText("Folder empty");
		}

	}

	private void initalGridView() {
		gridView.setVisibility(GridView.VISIBLE);
		listView.setVisibility(ListView.GONE);
		listDetailView.setVisibility(ListView.GONE);
		txtViewEmpty.setVisibility(TextView.GONE);
		if(Tool.ftp_path.size()==0 && listserver.size()>0){
			adapter = new FtpFileAdapter(FtpActivity.this, R.layout.grid_detail, listserver);
			gridView.setAdapter(adapter);
			gridView.setOnItemClickListener(onListFileClick());
			gridView.setOnItemLongClickListener(itemLongClick());
		}
		else if(list_ftp!=null && list_ftp.size()>0){
			ftpItemServerAdapter = new FtpItemServerAdapter(this, R.layout.grid_detail, list_ftp);
			gridView.setAdapter(ftpItemServerAdapter);
			gridView.setOnItemClickListener(onListFileItemClick());
			gridView.setOnItemLongClickListener(itemFileLongClick());
		}
		else{
			System.out.println(" vao day khong the");
			gridView.setVisibility(GridView.GONE);
			txtViewEmpty.setVisibility(TextView.VISIBLE);
			txtViewEmpty.setText("Folder empty");
		}

	}

	private void initalDetailView() {
		gridView.setVisibility(GridView.GONE);
		listView.setVisibility(ListView.GONE);
		listDetailView.setVisibility(ListView.VISIBLE);
		txtViewEmpty.setVisibility(TextView.GONE);

		if(Tool.ftp_path!=null && Tool.ftp_path.size()==0 && listserver.size()>0){
			adapter = new FtpFileAdapter(FtpActivity.this, R.layout.list_detail, listserver);
			listDetailView.setAdapter(adapter);
			listDetailView.setOnItemClickListener(onListFileClick());
			listDetailView.setOnItemLongClickListener(itemLongClick());
		}
		else if(list_ftp!=null && list_ftp.size()>0){
			System.out.println(" detail");
			ftpItemServerAdapter = new FtpItemServerAdapter(this, R.layout.list_detail, list_ftp);
			listDetailView.setAdapter(ftpItemServerAdapter);
			listDetailView.setOnItemClickListener(onListFileItemClick());
			listDetailView.setOnItemLongClickListener(itemFileLongClick());
		}else{
			System.out.println(" vao day khong the");
			listDetailView.setVisibility(ListView.GONE);
			txtViewEmpty.setVisibility(TextView.VISIBLE);
			txtViewEmpty.setText("Folder empty");
		}

	}


	// process button
	public void processButton(){
		switchButton.setOnClickListener(processSwitchButton());
		expandButton.setOnClickListener(processButtonExpand());
		sortButton.setOnClickListener(processSortButton());
		changeViewButton.setOnClickListener(processChangeViewButton());
		backButton.setOnClickListener(processBackButton());
		mBackButton.setOnClickListener(processBackButton());
		multiButton.setOnClickListener(proccessMutilButton());
		mCancelButton.setOnClickListener(processCancelButton());
		mDeleteButton.setOnClickListener(processDeleteButton());
		mCopyButton.setOnClickListener(processCopyButton());
	}

	// process button expand
	public OnClickListener processButtonExpand(){
		OnClickListener onclick = new  View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if(expandLayout.getVisibility()==LinearLayout.GONE){
					expandLayout.setVisibility(LinearLayout.VISIBLE);
					expandButton.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.drawable.subtract), null,null);
				}else{
					expandLayout.setVisibility(LinearLayout.GONE);
					expandButton.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.drawable.plus), null,null);
				}
			}
		};
		return onclick;
	}

	private OnClickListener processSwitchButton() {
		OnClickListener action = new OnClickListener() {

			public void onClick(View v) {
				ftpConnectSQLITE.close();
				String[] list = new String[] { "Local", "LAN", "FTP" };
				dialog = new Dialog(FtpActivity.this);
				dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
				dialog.setContentView(R.layout.popup_switch);
				((TextView)dialog.findViewById(R.id.tvHeader)).setText(R.string.switch_to);
				ListView listview = (ListView) dialog.findViewById(R.id.lvSwith);
				listview.setAdapter(new ArrayAdapter<String>(FtpActivity.this,
						android.R.layout.select_dialog_singlechoice, list));
				listview.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
				listview.setItemChecked(2, true);
				listview.setOnItemClickListener(switchToClick());
				((Button) dialog.findViewById(R.id.cancel)).setOnClickListener(new OnClickListener() {					

					public void onClick(View v) {
						dialog.dismiss();
					}
				});
				dialog.setCanceledOnTouchOutside(true);
				dialog.show();
			}
		};
		return action;
	}
	private OnItemClickListener switchToClick() {
		OnItemClickListener action = new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if (arg2==0) {
					ftpConnectSQLITE.close();
					Intent intent = new Intent(FtpActivity.this, LocalActivity.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);
					return;
				}if (arg2==1){
					Intent intent = new Intent(FtpActivity.this, LanActivity.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);
					return;
				}if (arg2==2){
					dialog.dismiss();
					return;
				}
				dialog.dismiss();
				finish();
			}
		};
		return action;
	}

	public OnClickListener processSortButton(){
		OnClickListener onclick = new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				String[] list = new String[] {getResources().getString(R.string.name),getResources().getString(R.string.size), getResources().getString(R.string.lastmodified) };
				dialog = new Dialog(FtpActivity.this);
				dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
				dialog.setContentView(R.layout.popup_switch);
				((TextView)dialog.findViewById(R.id.tvHeader)).setText(R.string.sort);

				ListView listview = (ListView) dialog.findViewById(R.id.lvSwith);
				listview.setAdapter(new ArrayAdapter<String>(FtpActivity.this,
						android.R.layout.select_dialog_singlechoice, list));
				listview.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
				listview.setItemChecked(sortlist, true);
				listview.setOnItemClickListener(sortClick());

				((Button)dialog.findViewById(R.id.cancel)).setOnClickListener(new OnClickListener() {					

					public void onClick(View v) {
						dialog.dismiss();
					}
				});
				dialog.setCanceledOnTouchOutside(true);
				dialog.show();
			}
		};
		return onclick;
	}

	public OnClickListener processChangeViewButton(){
		OnClickListener action = new OnClickListener() {

			@Override
			public void onClick(View view) {
				try {
					String[] list = new String[] {getResources().getString(R.string.girdview),getResources().getString(R.string.listview), 
							getResources().getString(R.string.detailview) };
					dialog = new Dialog(FtpActivity.this);
					dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
					dialog.setContentView(R.layout.popup_switch);
					((TextView)dialog.findViewById(R.id.tvHeader)).setText(R.string.changeView);
					ListView listview = (ListView) dialog.findViewById(R.id.lvSwith);
					listview.setAdapter(new ArrayAdapter<String>(FtpActivity.this,R.layout.list_option,list));
					listview.setOnItemClickListener(changeViewClick());
					((Button) dialog.findViewById(R.id.cancel)).setOnClickListener(new OnClickListener() {					

						public void onClick(View v) {
							dialog.dismiss();
						}
					});
					dialog.setCanceledOnTouchOutside(true);
					dialog.show();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		return action;
	}

	private OnItemClickListener changeViewClick(){
		OnItemClickListener action =new  OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if (arg2==0) {
					LoadSetting.setting.setDisplay(0);
				}
				if (arg2==1) {
					LoadSetting.setting.setDisplay(1);
				}
				if (arg2==2) {
					LoadSetting.setting.setDisplay(2);
				}
				UsersDAO user  = new UsersDAO(FtpActivity.this);
				user.saveData(LoadSetting.setting.getBackground(), LoadSetting.setting.getDisplay(), LoadSetting.setting.getLanguage(), LoadSetting.setting.getIcon());
				refreshItemServerFTP(Tool.connect);
				dialog.dismiss();
			}
		};
		return action;
	}

	public OnClickListener processBackButton(){
		OnClickListener onclick = new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				back();
			}
		};
		return onclick;
	}

	private OnItemClickListener sortClick() {
		OnItemClickListener action = new OnItemClickListener() {			
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				switch (arg2) {
				case 0:
					list_ftp = Tool.sortFTP(list_ftp, 0);
					sortlist = 0;
					break;
				case 1:
					list_ftp = Tool.sortFTP(list_ftp, 1);
					sortlist = 1;
					break;
				case 2:
					list_ftp = Tool.sortFTP(list_ftp, 2);
					sortlist = 2;
					break;
				}	

				refreshAdapter(Tool.connect);
				dialog.dismiss();
			}	
		};

		return action;

	}

	public void refreshAdapter(FtpConnect connect){
		switch (LoadSetting.setting.getDisplay()) {
		case 0:
			initalGridView();
			break;
		case 1:
			initalListView();
			break;
		case 2:
			initalDetailView();
			break;
		default:
			break;
		}	
	}

	// mutil button
	public OnClickListener proccessMutilButton(){
		OnClickListener onclick = new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				multi = true;
				multiAction = 0;
				flagCopyCut = 0;
				multiSelect.clear();
				tongmulti=0;

				((LinearLayout)findViewById(R.id.multiLayout))
				.setVisibility(LinearLayout.VISIBLE);
				((LinearLayout)findViewById(R.id.normalLayout))
				.setVisibility(LinearLayout.GONE);
				Toast.makeText(FtpActivity.this, R.string.multion, Toast.LENGTH_SHORT)
				.show();				
			}
		};
		return onclick;
	}
	// process cancel button
	public OnClickListener processCancelButton(){
		OnClickListener onclick = new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				multi = false;
				multiAction = 0;
				flagCopyCut = 0;
				multiSelect.clear();
				((LinearLayout)findViewById(R.id.multiLayout))
				.setVisibility(LinearLayout.GONE);
				((LinearLayout)findViewById(R.id.normalLayout))
				.setVisibility(LinearLayout.VISIBLE);
				Toast.makeText(FtpActivity.this, R.string.multioff, Toast.LENGTH_SHORT)
				.show();
				for(FtpConnect t:list_ftp){
					if(t.isChecked())t.setChecked(false);
				}
				ftpItemServerAdapter.notifyDataSetChanged();
			}
		};
		return onclick;
	}
	
	//process delete button
	public OnClickListener processDeleteButton(){
		OnClickListener onclick = new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				AlertDialog.Builder builder = new AlertDialog.Builder(FtpActivity.this);
				builder.setTitle(getString(R.string.delete));
				builder.setMessage(getString(R.string.areyousure));
				builder.setPositiveButton(getString(R.string.ok),
						new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						if(multi){
							if(multiSelect != null && multiSelect.size() >0){
								for (int i = 0; i < multiSelect.size(); i++) {
									Tool.dodelete(multiSelect.get(i).getFtpFile(), Tool.getFTPPath(Tool.ftp_path));
								}
								multi=false;
								refreshItemServerFTP(Tool.connect);
								multiSelect.clear();
								((LinearLayout)findViewById(R.id.multiLayout))
								.setVisibility(LinearLayout.GONE);
								((LinearLayout)findViewById(R.id.normalLayout))
								.setVisibility(LinearLayout.VISIBLE);
								Toast.makeText(FtpActivity.this, R.string.multioff, Toast.LENGTH_SHORT)
								.show();
							}
						}
					}
				});
				builder.setNegativeButton(getString(R.string.cancel), null);
				builder.show();
			}
		};
		return onclick;
	}

	// item long click
	public OnItemLongClickListener itemLongClick(){
		OnItemLongClickListener onclick = new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> adapterview, View view,
					int position, long arg3) {
				FtpConnect ftpConnect = (FtpConnect) adapterview.getItemAtPosition(position); 
				processOnLongClick(ftpConnect);
				return true;
			}
		};
		return onclick;
	}

	// process copy
//	String srcpath="",destpath="";
//	ArrayList<String> srcpath_array = new ArrayList<String>();
	public OnClickListener processCopyButton(){
		OnClickListener listener = new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				try {
					if(multiSelect!=null && multiSelect.size()>0){
						multiAction = 1; // 1 la copy
						flagCopyCut = 0;
						multi = false;
						Tool.multiSelect.clear();
						Tool.multiSelect.addAll(multiSelect);
						Tool.src_ftp_path=Tool.getFTPPath(Tool.ftp_path);
						
//						srcpath_array.clear();
//						srcpath_array=Tool.ftp_path;
//						srcpath=Tool.getFTPPath(Tool.ftp_path);
//						System.out.println("nguon: "+srcpath);
//						for(int i=0;i<srcpath_array.size();i++){
//							System.out.println(i+" : "+srcpath_array.get(i));
//							System.out.println(Tool.connect.getHostname());
//						}
						((LinearLayout) FtpActivity.this.findViewById(R.id.multiLayout))
						.setVisibility(LinearLayout.GONE);
						((LinearLayout) FtpActivity.this.findViewById(R.id.normalLayout))
						.setVisibility(LinearLayout.VISIBLE);
						Toast.makeText(FtpActivity.this, R.string.multioff, Toast.LENGTH_SHORT)
						.show();
						String[] list ={"Local","FTP","LAN"};
						dialog = new Dialog(FtpActivity.this);
						dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
						dialog.setContentView(R.layout.popup_switch);
						((TextView)dialog.findViewById(R.id.tvHeader)).setText(R.string.option);
						ListView listview = (ListView) dialog.findViewById(R.id.lvSwith);
						listview.setAdapter(new ArrayAdapter<String>(FtpActivity.this,R.layout.list_option,list));
						listview.setOnItemClickListener(processClickOption());
						((Button) dialog.findViewById(R.id.cancel)).setOnClickListener(new OnClickListener() {					

							public void onClick(View v) {
								dialog.dismiss();
							}
						});
						dialog.setCanceledOnTouchOutside(true);
						dialog.show();
					}else{
						AlertDialog.Builder builder = new AlertDialog.Builder(FtpActivity.this);
						builder.setTitle(FtpActivity.this.getString(R.string.warning));
						builder.setMessage(FtpActivity.this.getString(R.string.chooseafilecopy));
						builder.show();
						return;
					}
					
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		return listener;
	}
	
	public OnItemClickListener processClickOption(){
		OnItemClickListener clickListener = new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				switch (position) {
				case 0:
					// local
					loadListLocalPopup();
					break;
				case 1:
					// ftp
					loadListFTPServerPopup();
					break;
				case 2:
					// LAN
					break;
				default:
					break;
				}
			}
		};
		return clickListener;
	}
	
	public void loadListFTPServerPopup(){
		try {
			ftpConnectSQLITE.open();
			listserver=(ArrayList<FtpConnect>) ftpConnectSQLITE.getAllConnect();
			
			dialog = new Dialog(FtpActivity.this);
			dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
			dialog.setContentView(R.layout.popup_switch);
			((TextView)dialog.findViewById(R.id.tvHeader)).setText(R.string.option);
			ListView listview = (ListView) dialog.findViewById(R.id.lvSwith);
			listview.setAdapter(new ArrayAdapter<FtpConnect>(FtpActivity.this,R.layout.list_option,listserver));
			listview.setOnItemClickListener(loadListFTPServerPopupDetail());
			((Button) dialog.findViewById(R.id.cancel)).setOnClickListener(new OnClickListener() {					

				public void onClick(View v) {
					dialog.dismiss();
				}
			});
			dialog.setCanceledOnTouchOutside(true);
			dialog.show();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void loadListLocalPopup(){
		
		Tool.dest_ftp_path_popup= new ArrayList<String>();
		Tool.dest_ftp_path=Environment.getExternalStorageDirectory().toString();
		String[] tem= Tool.dest_ftp_path.split(File.separator);
		if(tem!=null && tem.length>0){
			for(String s: tem){
				if(!s.equals(null) && !s.equals("")){
					Tool.dest_ftp_path_popup.add(s);
				}
			}
		}
		Intent intent = new Intent(FtpActivity.this, CopyLocalPopup.class);
		startActivity(intent);
		
	}
	
	public OnItemClickListener loadListFTPServerPopupDetail(){
		OnItemClickListener clickListener = new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
//				Tool.connect = (FtpConnect)arg0.getItemAtPosition(arg2);
//				Tool.ftp_path_popup.add(File.separator);
//				Intent intent = new Intent(FtpActivity.this, CopyFTPPopup.class);
//				intent.putExtra("ftpconnect", Tool.connect);
////				intent.putExtra("tool_ftp", "/");
//				startActivity(intent);
				Tool.dest_connect_popup=(FtpConnect)arg0.getItemAtPosition(arg2);
				Tool.dest_ftp_path_popup.clear();
				Tool.dest_ftp_path_popup.add(File.separator);
				Intent intent = new Intent(FtpActivity.this, CopyFTPPopup.class);
				startActivity(intent);
				
			}
		};
		return clickListener;
	}
	
	// process on long click
	public void processOnLongClick(final FtpConnect connect){
		try {
			String[] list = getResources().getStringArray(R.array.option_server);
			dialog = new Dialog(this);
			dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
			dialog.setContentView(R.layout.popup_switch);
			((TextView)dialog.findViewById(R.id.tvHeader)).setText(R.string.option);
			ListView listview = (ListView) dialog.findViewById(R.id.lvSwith);
			listview.setAdapter(new ArrayAdapter<String>(this,R.layout.list_option,list));
			listview.setOnItemClickListener(longMenuClick(connect));
			((Button) dialog.findViewById(R.id.cancel)).setOnClickListener(new OnClickListener() {					

				public void onClick(View v) {
					dialog.dismiss();
				}
			});
			dialog.setCanceledOnTouchOutside(true);
			dialog.show();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public OnItemClickListener longMenuClick(final FtpConnect connect){
		OnItemClickListener onclick = new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				switch (arg2) {
				case 0:
					proccessEdit(connect);
					break;
				case 1:
					proccessDelete(connect);
					break;

				default:
					break;
				}
			}
		};
		return onclick;
	}

	// process edit
	public void proccessEdit(final FtpConnect ftpConnect){
		Intent intent = new Intent(FtpActivity.this, EditServerFTP.class);
		intent.putExtra("ftp",ftpConnect);
		startActivity(intent);
	}
	// process delete 
	public void proccessDelete(final FtpConnect ftpConnect){
		AlertDialog.Builder builder = new AlertDialog.Builder(FtpActivity.this);
		builder.setTitle(getString(R.string.delete));
		builder.setMessage(getString(R.string.areyousure));
		builder.setCancelable(false);

		builder.setPositiveButton(getString(R.string.ok),new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				ftpConnectSQLITE.deleteFtp(ftpConnect);
				refreshFTP();
			}
		});

		builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {

			}
		});

		AlertDialog alertDialog = builder.create();
		alertDialog.show();
	}

	// process on list file click
	public OnItemClickListener onListFileClick(){
		OnItemClickListener onclick = new OnItemClickListener() {

			@Override
			public void onItemClick(final AdapterView<?> arg0, View arg1, final int arg2,
					long arg3) {


				FtpActivity.this.getAlertwaiting().show();
				try{
					new Thread(){
						public void run() {
							Tool.connect = (FtpConnect)arg0.getItemAtPosition(arg2);
							Tool.ftp_path.add(File.separator);

							FtpActivity.this.getUiHandler().post(new Runnable() {

								@Override
								public void run() {
									if(FtpActivity.this.isUpdateRequired){

									}else{
										refreshItemServerFTP(Tool.connect);
										FtpActivity.this.getAlertwaiting().cancel();
									}
								}
							});
						}
					}.start();
				}catch (Exception e) {
				}
			}
		};
		return onclick;
	}
	// process on list file item click
	public OnItemClickListener onListFileItemClick(){
		OnItemClickListener onclick = new OnItemClickListener() {

			@Override
			public void onItemClick(final AdapterView<?> arg0, View arg1, final int postion,
					long arg3) {
				Tool.connect = (FtpConnect)arg0.getItemAtPosition(postion);
				if (multi) {
					if(multiSelect!=null){
						list_ftp.get(postion).setChecked(!list_ftp.get(postion).isChecked());
						if(multiSelect.contains(Tool.connect)){
							multiSelect.remove(Tool.connect);
//							tongmulti-=Tool.connect.getTotalsize();
						}else{
							multiSelect.add(Tool.connect);
//							tongmulti+=Tool.connect.getTotalsize();
						}
					}
					ftpItemServerAdapter.notifyDataSetChanged();
					System.out.println("multi size: "+multiSelect.size()+" -- "+tongmulti);
				}
				else{
					Tool.ftp_path.add(Tool.connect.getFtpFile().getName());
					FtpActivity.this.getAlertwaiting().show();
					try{
						new Thread(){
							public void run() {


								FtpActivity.this.getUiHandler().post(new Runnable() {

									@Override
									public void run() {
										if(FtpActivity.this.isUpdateRequired){
										}else{
											if(Tool.connect.getFtpFile().isDirectory()){
												refreshItemServerFTP(Tool.connect);
											}else{

												asyntask = new AsyncTask<String, String, String>() {

													protected void onPreExecute() {
														showDialog(DIALOG_GETTING_FILE);
													}

													protected void onProgressUpdate(String... progress) {
														mProgressDialog.setProgress(Integer.parseInt(progress[0]));
													}
													void process(){
														try {
															boolean flag = Tool.connects();
															if (flag==true){
																File f = new File(Environment.getExternalStorageDirectory()+File.separator+"elifiledownload"+File.separator);

																if(!f.exists()){
																	f.mkdir();
																}

																f = new File(Environment.getExternalStorageDirectory()+File.separator+"elifiledownload"+File.separator+Tool.connect.getFtpFile().getName());
																if(!f.exists()){
																	f.createNewFile();
																}

																BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(f));
																InputStream input =Tool.client.retrieveFileStream(Tool.getFTPPath(Tool.ftp_path));

																byte[] buffer = new byte[1024];
																int len1 = 0;
																long total = 0;				        
																while ((len1 = input.read(buffer)) > 0) {
																	total += len1;
																	publishProgress(""+((total*100)/Tool.connect.getFtpFile().getSize()));
																	output.write(buffer, 0, len1);
																}
																if(output!=null)output.close();
																if(input!=null)input.close();


																if(f.canRead()){
																	Intent intent = new Intent(Intent.ACTION_VIEW);
																	if(Tool.checkExtendFile(Tool.connect.getFtpFile().getName(), ".txt")){
																		intent.setDataAndType(Uri.fromFile(f),"text/*");

																	}else if(Tool.checkExtendFile(Tool.connect.getFtpFile().getName(), ".xml")){
																		intent.setDataAndType(Uri.fromFile(f),"text/*");
																	}else if(Tool.checkExtendFile(Tool.connect.getFtpFile().getName(), ".apk")){
																		intent.setDataAndType(Uri.fromFile(f),"application/vnd.android.package-archive");
																	}

																	else if (Tool.checkExtendFile(Tool.connect.getFtpFile().getName(), ".FLV")
																			|| Tool.checkExtendFile(Tool.connect.getFtpFile().getName(), ".3gp")
																			|| Tool.checkExtendFile(Tool.connect.getFtpFile().getName(), ".avi")) {
																		intent.setDataAndType(Uri.fromFile(f), "video/*");
																	} else if (Tool.checkExtendFile(Tool.connect.getFtpFile().getName(), ".mp3")) {
																		intent.setDataAndType(Uri.fromFile(f), "audio/*");
																	} else if (Tool.checkExtendFile(Tool.connect.getFtpFile().getName(), ".doc")
																			|| Tool.checkExtendFile(Tool.connect.getFtpFile().getName(), ".docx")) {
																		intent.setDataAndType(Uri.fromFile(f), "text/*");
																	} else if (Tool.checkExtendFile(Tool.connect.getFtpFile().getName(), ".ppt")
																			|| Tool.checkExtendFile(Tool.connect.getFtpFile().getName(), ".pptx")) {
																		intent.setDataAndType(Uri.fromFile(f), "text/*");
																	} else if (Tool.checkExtendFile(Tool.connect.getFtpFile().getName(), ".xls")
																			|| Tool.checkExtendFile(Tool.connect.getFtpFile().getName(), ".xlsx")) {
																		intent.setDataAndType(Uri.fromFile(f), "text/*");
																	} else if (Tool.checkExtendFile(Tool.connect.getFtpFile().getName(), ".zip")
																			|| Tool.checkExtendFile(Tool.connect.getFtpFile().getName(), ".rar")) {
																		intent.setDataAndType(Uri.fromFile(f), "video/*");
																	} else if (Tool.checkExtendFile(Tool.connect.getFtpFile().getName(), ".jpg")
																			|| Tool.checkExtendFile(Tool.connect.getFtpFile().getName(), ".jpeg")
																			|| Tool.checkExtendFile(Tool.connect.getFtpFile().getName(), ".png")
																			|| Tool.checkExtendFile(Tool.connect.getFtpFile().getName(), ".bmp")
																			|| Tool.checkExtendFile(Tool.connect.getFtpFile().getName(), ".gif")) {
																		intent.setDataAndType(Uri.fromFile(f), "image/*");
																	}
																	startActivity(intent);
																}
															}	
															else{
																System.out
																.println(" connect fail");
															}
															if(Tool.client.isConnected()){
																Tool.client.logout();
															}
														} catch (Exception e) {
															e.printStackTrace();
														}
													}

													protected String doInBackground(String... params) {
														process();				
														return null;
													}

													protected void onPostExecute(String unused) {
														dismissDialog(DIALOG_GETTING_FILE);
														finish();
													}

												};		
												asyntask.execute("");	

												//											}


											}

											//										int a = checkExistFile(Tool.connect, Tool.list_history_ftp);
											//										if (a != -1)
											//											Tool.list_history_ftp.remove(a);
											Tool.connect.setName( Tool.connect+Tool.getFTPPath(Tool.ftp_path));
											Tool.list_history_ftp.add(Tool.connect);

											FtpActivity.this.getAlertwaiting().cancel();
										}
									}
								});
							}
						}.start();
					}catch (Exception e) {
					}
				}
			}
		};
		return onclick;
	}

	// check exit file
	//	private int checkExistFile(FtpConnect file, ArrayList<FtpConnect> arr) {
	//		if (file != null && arr.size() > 0) {
	//			for (FtpConnect f : arr) {
	//				System.out.println(" file path === " + file.getPath());
	//				System.out.println(" f path == " + f.getPath());
	//				if (file.getPath().equals(f.getPath())) {
	//					return arr.indexOf(f);
	//				}
	//			}
	//		}
	//		return -1;
	//	}

	// process item long lick
	public OnItemLongClickListener itemFileLongClick(){
		OnItemLongClickListener onclick = new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				Tool.connect = (FtpConnect)arg0.getItemAtPosition(arg2);
				processOnLongClickItemFtp(Tool.connect);
				return true;
			}
		};
		return onclick;
	}

	public void processOnLongClickItemFtp(FtpConnect ftpcnn){
		try {
			String[] list = getResources().getStringArray(R.array.option_arr);
			dialog = new Dialog(this);
			dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
			dialog.setContentView(R.layout.popup_switch);
			((TextView)dialog.findViewById(R.id.tvHeader)).setText(R.string.option);
			ListView listview = (ListView) dialog.findViewById(R.id.lvSwith);
			listview.setAdapter(new ArrayAdapter<String>(this,R.layout.list_option,list));
			listview.setOnItemClickListener(processlongMenuClick(ftpcnn));
			((Button) dialog.findViewById(R.id.cancel)).setOnClickListener(new OnClickListener() {					

				public void onClick(View v) {
					dialog.dismiss();
				}
			});
			dialog.setCanceledOnTouchOutside(true);
			dialog.show();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public OnItemClickListener processlongMenuClick(final FtpConnect ftp){
		OnItemClickListener onclick = new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				switch (arg2) {
				case 0:

					break;
				case 1:

					break;
				case 2:
					delete(ftp);
					break;
				case 3:
					rename(ftp);
					break;
				case 4:
					detail(ftp);
					break;
				case 5:
					if(!ftp.isFavorite()){
						saveFavorite(ftp);
						ftp.setFavorite(true);
					}else{
						saveFavorite(ftp);
						ftp.setFavorite(false);
					}
					adapter.notifyDataSetChanged();
					break;
				default:
					break;
				}
				if(dialog.isShowing())dialog.dismiss();
			}
		};
		return onclick;
	}

	// process rename 
	public void rename(final FtpConnect ftp){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		final EditText input = new EditText(this);

		String fileName = "";
		String extension = "";
		fileName = ftp.getFtpFile().getName();
		if (!ftp.getFtpFile().isDirectory()) {
			int index = ftp.getFtpFile().getName().lastIndexOf(".");
			fileName = ftp.getFtpFile().getName().substring(0, index);
			extension = ftp.getFtpFile().getName()
			.substring(index, ftp.getFtpFile().getName().length());
		}

		final String ex = extension;

		input.setText(fileName);
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.FILL_PARENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);
		input.setLayoutParams(lp);
		input.setLines(1);
		input.setSingleLine(true);
		builder.setView(input);
		builder.setTitle(getString(R.string.file_name));
		builder.setPositiveButton(getString(R.string.ok),
				new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				if (input.getText().toString() == null
						|| input.getText().toString().trim().equals("")) {
					return;
				}
				for (int i = 0; i < list_ftp.size(); i++) {
					if (list_ftp.get(i).equals(
							input.getText().toString().trim())) {
						checkExitRename();
						return;
					}
				}
				String src =  Tool.getFTPPath(Tool.ftp_path)+File.separator
				+ ftp.getFtpFile().getName();

				String des =  Tool.getFTPPath(Tool.ftp_path)+File.separator
				+ input.getText().toString().trim() + ex;


				processRename(src, des);
			}
		});
		builder.setNegativeButton(getString(R.string.cancel), null);
		builder.show();
	}

	public void checkExitRename() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.warning);
		builder.setMessage(R.string.fileexist);
		builder.setPositiveButton(R.string.ok, null);
		builder.show();
	}
	public void processRename(final String src, final String des) {
		asyn = new AsyncTask<String, String, Void>() {

			protected void onPreExecute() {
				mProgressDialog = ProgressDialog.show(FtpActivity.this, "",
						"Renaming...", true);
			}

			protected void onProgressUpdate(String... progress) {
				mProgressDialog.setMessage(progress[0]);
			}


			protected Void doInBackground(String... params) {

				publishProgress(getResources().getString(
						R.string.renaming));
				try {
					boolean flag = Tool.connects();

					if (flag) {
						flag = Tool.client.rename(src, des);
						if (flag) {
							publishProgress("Rename Complete");
						} else {
							publishProgress("Cannot rename");
						}
					} else {
						publishProgress("Connection failed, please check again");
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				return null;
			}


			protected void onPostExecute(Void arg) {
				if (mProgressDialog.isShowing()) {
					mProgressDialog.dismiss();
					refreshItemServerFTP(Tool.connect);
				}
			}
		};
		asyn.execute("");
	}

	// detail
	public void detail(FtpConnect ftp){
		int lbwidth=screenwidth/3+10;
		int tvwidth=screenwidth-screenwidth/3;

		LayoutInflater inflater = (LayoutInflater)getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
		View viewDelete = inflater.inflate(R.layout.detail_item_ftp, null);

		final TextView fname = (TextView)viewDelete.findViewById(R.id.idfilename);
		final TextView ftype = (TextView)viewDelete.findViewById(R.id.idtypefile);
		final TextView fsize = (TextView)viewDelete.findViewById(R.id.idsize);
		final TextView fmodify = (TextView)viewDelete.findViewById(R.id.idmodifydate);
		final TextView flocation = (TextView)viewDelete.findViewById(R.id.idlocationname);

		fname.setText(getString(R.string.file_name)+":");
		ftype.setText(getString(R.string.filetype)+":");
		fsize.setText(getString(R.string.filesize)+":");
		fmodify.setText(getString(R.string.lastmodified)+":");
		flocation.setText(getString(R.string.location)+":");

		final TextView vfname = (TextView)viewDelete.findViewById(R.id.valuenamefile);
		final TextView vftype = (TextView)viewDelete.findViewById(R.id.valuetypefile);
		final TextView vfSize = (TextView)viewDelete.findViewById(R.id.valuesize);
		final TextView vfModify = (TextView)viewDelete.findViewById(R.id.valuemodifydate);
		final TextView vlocation= (TextView)viewDelete.findViewById(R.id.valuenamelocation);

		vfname.setText(ftp.getFtpFile().getName().toString());
		vlocation.setText(Tool.connect.getHostname()+Tool.getFTPPath(Tool.ftp_path));

		if(ftp.getFtpFile().isDirectory()){
			vftype.setText(getString(R.string.folder));
		}else if(ftp.getFtpFile().isFile()){
			vftype.setText(getString(R.string.file));
		}

		if(ftp.getFtpFile().isFile()){
			if(ftp.getFtpFile().getSize()<1024){
				vfSize.setText(ftp.getFtpFile().getSize() + " bytes");	
			}else{
				vfSize.setText((ftp.getFtpFile().getSize()) / (1024)+ " KB");
			}
		}else if(ftp.getFtpFile().isDirectory()){
			fsize.setVisibility(TextView.GONE);
			vfSize.setVisibility(TextView.GONE);
		}

		vfModify.setText(Tool.format1.format(ftp.getFtpFile().getTimestamp().getTime()));

		fname.setWidth(lbwidth);
		vfname.setWidth(tvwidth);

		flocation.setWidth(lbwidth);
		vlocation.setWidth(tvwidth);

		ftype.setWidth(lbwidth);
		vftype.setWidth(tvwidth);

		fsize.setWidth(lbwidth);
		vfSize.setWidth(tvwidth);

		fmodify.setWidth(lbwidth);
		vfModify.setWidth(tvwidth);

		AlertDialog.Builder builderDetail = new AlertDialog.Builder(this);
		builderDetail.setTitle(ftp.getFtpFile().getName().toString()+" "+"properties");
		builderDetail.setView(viewDelete);

		builderDetail.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {

			}
		});
		AlertDialog al = builderDetail.create();
		al.show();
	}

	public boolean saveFavorite(FtpConnect ftp){
		try {
			//			favoriteConnectSQLiteFTP.createNewFavoriteFTP(ftp);
			ftpConnectSQLITE.createNewFavoriteFTP(ftp);
			Toast.makeText(this, "Saved", Toast.LENGTH_LONG).show();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} 
		return true;
	}

	public ArrayList<FtpConnect> getAllFavorite(){
		Tool.list_favorite_ftp = (ArrayList<FtpConnect>)ftpConnectSQLITE.getAllConnectFavorite(Tool.connect.getHostname());
		System.out.println("list favorite ==== " + Tool.list_favorite_ftp.size());
		return Tool.list_favorite_ftp;
	}

	// process button address
	public OnClickListener processButtonAddress(){
		OnClickListener onclick = new OnClickListener() {

			@Override
			public void onClick(View v) {
				Tool.list_favorite_ftp = getAllFavorite();
				Intent intent = new Intent(getApplicationContext(), AddressFTPActivity.class);
				startActivity(intent);
			}
		};
		return onclick;
	}


	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.menu_ftp, menu);
		setMenuBackground();
		return super.onCreateOptionsMenu(menu);
	}

	protected void setMenuBackground(){
		Log.d("", "Enterting setMenuBackGround");  
		getLayoutInflater().setFactory( new Factory() {  

			@Override
			public View onCreateView(String name, Context context,
					AttributeSet attrs) {
				if ( name.equalsIgnoreCase( "com.android.internal.view.menu.IconMenuItemView" ) ) {  

					try { 
						LayoutInflater f = getLayoutInflater();  
						final View view = f.createView( name, null, attrs );  
						new Handler().post( new Runnable() {  
							public void run () {  
								view.setBackgroundResource( R.color.menu_option_background);  
							}  
						} );  
						return view;  
					}  
					catch ( InflateException e ) {}  
					catch ( ClassNotFoundException e ) {}  
				}  
				return null;  

			}  
		});  
	}

	// process delete
	public void delete(final FtpConnect ftp){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(getString(R.string.delete));
		builder.setMessage(getString(R.string.areyousure));
		builder.setPositiveButton(getString(R.string.ok),
				new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				if(multi){
					if(multiSelect != null && multiSelect.size() >0){
						for (int i = 0; i < multiSelect.size(); i++) {
							Tool.dodelete(multiSelect.get(i).getFtpFile(), Tool.getFTPPath(Tool.ftp_path));
						}
						multi=false;
						refreshItemServerFTP(Tool.connect);
						multiSelect.clear();
						((LinearLayout)findViewById(R.id.multiLayout))
						.setVisibility(LinearLayout.GONE);
						((LinearLayout)findViewById(R.id.normalLayout))
						.setVisibility(LinearLayout.VISIBLE);
						Toast.makeText(FtpActivity.this, R.string.multioff, Toast.LENGTH_SHORT)
						.show();
					}
				}else{
					Tool.dodelete(ftp.getFtpFile(),Tool.getFTPPath(Tool.ftp_path));
					refreshItemServerFTP(Tool.connect);
				}
			}
		});
		builder.setNegativeButton(getString(R.string.cancel), null);
		builder.show();
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_setting:
			Intent intent = new Intent(FtpActivity.this,SettingActivity.class);
			startActivity(intent);
			break;
		case R.id.menu_operator:
			operator();
			break;
		case R.id.menu_new:
			processNewFolder();
			break;
		case R.id.menu_refresh:
			if(Tool.ftp_path.size()==0){
				refreshFTP();
			}else{
				refreshItemServerFTP(Tool.connect);
			}
			Toast.makeText(this, getString(R.string.reload), Toast.LENGTH_SHORT).show();
			break;
		case R.id.menu_quit:
			runExit();
			break;
		}
		return true;
	}

	private void runExit(){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(getString(R.string.exitapp));
		builder.setMessage(getString(R.string.questionexitapp));
		builder.setPositiveButton(getString(R.string.ok),new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				FtpActivity.this.moveTaskToBack(true);
				android.os.Process.killProcess(android.os.Process.myPid());
				android.os.Process.sendSignal(android.os.Process.myPid(), android.os.Process.SIGNAL_KILL);
			}
		});
		builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
			}
		});
		AlertDialog alertDialog = builder.create();
		alertDialog.show();
	}

	public void processNewFolder(){
		if(Tool.ftp_path.size()==0){
			Intent intent = new Intent(FtpActivity.this, NewServerActivity.class);
			startActivity(intent);
		}else{
			LayoutInflater inflater = (LayoutInflater)getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
			View view = inflater.inflate(R.layout.newfolder,null);

			final TextView lbFolder = (TextView)view.findViewById(R.id.lbNameFolder);
			final EditText valueFolder = (EditText)view.findViewById(R.id.nameFolder);

			lbFolder.setText(getString(R.string.namefolder));
			lbFolder.setTextColor(Color.WHITE);

			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("Add a new folder name");
			builder.setView(view);
			builder.setCancelable(false);

			builder.setPositiveButton(getString(R.string.ok),new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					if((Tool.connect.getHostname()+File.separator).equals(Tool.getFTPPath(Tool.ftp_path)))
						ftpCreateFolder(Tool.getFTPPath(Tool.ftp_path)+valueFolder.getText().toString());
					else
						ftpCreateFolder(Tool.getFTPPath(Tool.ftp_path)+File.separator+valueFolder.getText().toString());

					refreshItemServerFTP(Tool.connect);
				}
			});
			builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {

				}
			});

			AlertDialog alertDialog = builder.create();
			alertDialog.show();
		}

	}

	public  void ftpCreateFolder(String fileRemotePath) {
		Tool.connects();
		try {
			if (!Tool.client.changeWorkingDirectory(fileRemotePath)) {
				Tool.client.makeDirectory(fileRemotePath);
			}else{
				AlertDialog.Builder builder = new AlertDialog.Builder(
						FtpActivity.this);
				builder.setTitle(R.string.duplicate);
				builder.setMessage(R.string.folderexist);
				builder.setPositiveButton(getString(R.string.ok), null);
				builder.show();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			Tool.closeconnect();

		}
	}

	public void operator() {
		if (operator != null) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle(R.string.operator);
			builder.setItems(operator, new DialogInterface.OnClickListener() {

				public void onClick(DialogInterface dialog, int which) {
					switch (which) {
					case 0:
						break;
					default:
						break;
					}
				}
			});
			builder.setPositiveButton(R.string.cancel, null);
			builder.show();
		} else {
			Toast.makeText(this, R.string.no_operator, Toast.LENGTH_SHORT).show();
		}
	}
	public void setValueOperator() {
		operator = null;
	}
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_GETTING_FILE:
			mProgressDialog = new ProgressDialog(this);
			mProgressDialog.setMessage(getResources().getString(R.string.gettingfile));
			mProgressDialog.setIndeterminate(false);
			mProgressDialog.setMax(100);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			mProgressDialog.setCancelable(true);
			mProgressDialog.show();
			return mProgressDialog;
		case DIALOG_PROGRESS:
			mProgressDialog = new ProgressDialog(this);
			mProgressDialog.setCancelable(false);
			mProgressDialog.show();
			return mProgressDialog;
		default:
			return null;
		}
	}

	@Override
	public void onBackPressed() {
		back();
	}

	public void back(){
		if(Tool.ftp_path.size()==1){
			Tool.ftp_path.clear();
			addressButton.setText(R.string.choose_machine);
			listserver = new ArrayList<FtpConnect>();
			expandLayout.setVisibility(LinearLayout.GONE);
			loadAllServer();
			refreshFTP();
		}else if(Tool.ftp_path.size()==0){
			Intent intent = new Intent(FtpActivity.this,LocalActivity.class);
			startActivity(intent);
			finish();
		}else if (Tool.ftp_path.size() > 1) {
			Tool.ftp_path.remove(Tool.ftp_path.size() - 1);
			refreshItemServerFTP(Tool.connect);
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		ftpConnectSQLITE.close();
	}
}
